package com.zyz.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyz.common.core.constants.CacheConstants;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.redis.service.RedisService;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.friend.mapper.question.QuestionMapper;
import com.zyz.friend.model.question.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class QuestionCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private QuestionMapper questionMapper;

    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        // 从数据库查询
        List<Question> questionList = questionMapper.selectList(
                new LambdaQueryWrapper<Question>().orderByDesc(Question::getCreateTime).select(Question::getQuestionId));
        if (CollectionUtil.isEmpty(questionList)) {
            // 数据库中没有任何题目
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        // 同步到questionCache中
        redisService.rightPushAll(CacheConstants.QUESTION_LIST, questionIdList);
    }

    public Long getPreQuestionId(Long questionId) {
        Long questionIndex = redisService.indexOf(CacheConstants.QUESTION_LIST, questionId);
        if (questionIndex == 0) {
            log.warn("当前题目为第一题");
            throw new ServiceException(ResultCodeEnum.FAILED_QUESTION_FIRST);
        }
        return redisService.index(CacheConstants.QUESTION_LIST, questionIndex - 1, Long.class);
    }

    public Long getNextQuestionId(Long questionId) {
        Long questionIndex = redisService.indexOf(CacheConstants.QUESTION_LIST, questionId);
        if (getListSize() - 1 == questionIndex) {
            log.warn("当前题目为最后一题");
            throw new ServiceException(ResultCodeEnum.FAILED_QUESTION_LAST);
        }
        return redisService.index(CacheConstants.QUESTION_LIST, questionIndex + 1, Long.class);
    }

    // 从redis中获取热点题目列表
    public List<Long> getQuestionHotList(Long end) {
        return redisService.getZSetList(CacheConstants.QUESTION_HOT, end).stream().map(obj -> (Long) obj).toList();
    }
}
